import { defineStore } from "pinia";
import pinia from "@/store";
import { userLogin } from "@/api/user";

import { LoginRequest, refreshUserInfo } from "@/api/user";

export interface UserState {
  username: string;
  accessToken: string;
  refreshToken?: string;
  roles: Array<string>;
}
export const useUserStoreHook = defineStore("userInfo", {
  state: ():UserState => {
    return {
      username: "大伟",
      accessToken: "",
      roles: ["common"],
    };
  },
  getters: {},
  actions: {
    storeUserLogin(data: LoginRequest) {
      return userLogin(data).then((res) => {
        this.username = res.username;
        this.accessToken = res.accessToken;
        this.roles = res.roles;
        return res;
      });
    },
    stroeRefreshUserInfo() {
      if (this.username === "大伟" && !this.accessToken) {
        refreshUserInfo({ accessToken: this.accessToken })
          .then((res) => {
            this.username = res.username;
            this.accessToken = res.accessToken;
            this.roles = res.roles;
          })
          .catch(() => {
            this.accessToken = "";
          });
      }
    },
    persist: {
      key: "userInfo",
      storage: sessionStorage,
      paths: ["accessToken"],
    },
  },
});

export function useUserStore() {
  return useUserStoreHook(pinia);
}
